<template>
  <div class="app-container">
    <el-form
      label-position="left"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="申请描述" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入申请描述"
          clearable
          @keyup.enter.native="handleFuzzyQuery"
        />
      </el-form-item>

      <el-form-item label="日期"
        ><el-date-picker
          v-model="queryParams.searchTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          align="center"
          @keyup.enter.native="handleFuzzyQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleFuzzyQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-goods"
          size="mini"
          @click="handleHistory"
          >历史记录</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
          >删除</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :data="orderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="订单类型" align="center" prop="orderType" /> -->
      <el-table-column label="发起者" align="center" prop="createBy" />
      <el-table-column
        label="订单描述"
        align="center"
        prop="description"
        show-overflow-tooltip="true"
      />
      <el-table-column label="状态" align="center" prop="status">
      </el-table-column>
      <el-table-column
        label="发起日期"
        align="center"
        prop="createTime"
        width="180px"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewDetail(scope.row)"
            v-hasPermi="['system:order:query']"
            >查看关联资源</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="allotRecycle(scope.row)"
            v-hasPermi="['system:order:query']"
            v-show="showButton"
            >分配回收</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewPreview(scope.row)"
            v-hasPermi="['system:order:query']"
            v-show="showButton"
            >查看支付预览</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAccept(scope.row)"
            v-hasPermi="['system:order:query']"
            v-show="showButton"
            >支付</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="目标商家">
          <el-select
            v-model="form.finisherId"
            placeholder="请选择目标商家"
            clearable
          >
            <el-option
              v-for="item in merchant"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <!-- <editor v-model="form.content" :min-height="192" /> -->
          <el-input
            v-model="form.description"
            placeholder="请输入申请描述"
            type="textarea"
          />
        </el-form-item>
        <el-form-item
          v-for="item in formItems"
          :label="item.label"
          :key="item.resourceId"
          v-show="showItem(item)"
        >
          <el-input v-model="form[item.model]"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配回收对话框 -->
    <el-dialog
      title="分配回收"
      :visible.sync="openRecycle"
      width="500px"
      append-to-body
    >
      <el-form
        ref="recycleForm"
        :model="recycleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="回收员" prop="">
          <!-- <editor v-model="form.content" :min-height="192" /> -->
          <el-input v-model="recycleForm.recycler" placeholder="请输入回收员" />
        </el-form-item>

        <el-form-item label="回收员联系方式" prop="recyclerContact">
          <el-input
            v-model="recycleForm.recyclerContact"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="回收日期" prop="endTime">
          <el-date-picker
            clearable
            v-model="recycleForm.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择回收日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRecycleForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看关联资源对话框 -->
    <el-dialog
      title="关联资源信息"
      :visible.sync="openDetail"
      width="80%"
      append-to-body
    >
      <el-table
        :data="relativeResource"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-table-column label="资源类型" align="center" prop="resourceType" />

        <el-table-column label="重量,单位千克" align="center" prop="weight" />
        <el-table-column label="价格,单位元/千克" align="center" prop="price" />
        <!-- 
        <el-table-column
          label="打包要求"
          align="center"
          prop="packageRequirements"
        /> -->
      </el-table>
    </el-dialog>

    <!-- 支付预览对话框 -->
    <el-dialog
      title="申请交易预览"
      :visible.sync="openPreview"
      width="80%"
      append-to-body
    >
      <el-table
        :data="previewList"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-table-column label="资源类型" align="center" prop="resourceType" />
        <!-- <el-table-column label="资源名" align="center" prop="name" /> -->
        <el-table-column
          label="预计收益（元）"
          align="center"
          prop="preIncome"
        />
        <el-table-column
          label="实际收益（元）"
          align="center"
          prop="actualIncome"
        />
        <el-table-column
          label="实际/预计百分比"
          align="center"
          prop="percentage"
        />
      </el-table>
    </el-dialog>

    <!-- 查看历史申请对话框 -->
    <el-dialog
      title="历史记录"
      :visible.sync="openHistory"
      width="80%"
      append-to-body
    >
      <el-table
        :data="historyList"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-table-column label="申请编号" align="center" prop="orderId" />

        <el-table-column label="申请描述" align="center" prop="description" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="完成时间" align="center" prop="updateTime" />
        <el-table-column label="预期收益" align="center" prop="preIncome" />
        <el-table-column label="实际收益" align="center" prop="actualIncome" />
        <el-table-column
          label="实际/预计百分比"
          align="center"
          prop="percentage"
        />
        <!-- 
        <el-table-column
          label="打包要求"
          align="center"
          prop="packageRequirements"
        /> -->
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listResource,
  getResource,
  delResource,
  addResource,
  updateResource,
  fuzzyListResource,
} from "@/api/system/resource";
import {
  listOrder,
  fuzzyListOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  listOrderResource,
  placeOrder,
  listOrderMine,
  fuzzyListOrderMine,
  selectMerchant,
  listHistory,
} from "@/api/system/order";
import {
  listDetail,
  getDetail,
  delDetail,
  addDetail,
  updateDetail,
  complete,
  allot,
  previewPay,
} from "@/api/system/detail";
import user from "@/store/modules/user";
import calc from "@/utils/index";

export default {
  name: "applied",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      orderList: [],
      // 当前行订单的关联资源
      relativeResource: [],

      //用户自己的资源列表
      ownResources: [],

      //  选中行的publisherId
      publisherIds: [],
      // 弹出层标题
      title: "",
      // 是否显示新增修改弹出层
      open: false,
      // 是否展示详情记录
      openDetail: false,

      //是否展示回收对话框
      openRecycle: false,
      //是否展示历史申请
      openHistory: false,

      //历史申请数组
      historyList: [],

      // 预览数组
      previewList: [],

      //是否已预览
      isPreview: false,
      //是否展示支付预览对话框
      openPreview: false,
      //商家列表
      merchant: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderType: null,
        publisherId: null,
        finisherId: null,
        description: null,
        searchTime: null,
        searchValue: null,
        status: 0,
      },
      // 表单参数
      form: {},
      recycleForm: {},
      // 表单校验publisherIDs
      rules: {
        // publisherId: [
        //   { required: true, message: "发布者id不能为空", trigger: "blur" },
        // ],
      },
      allotParams: {
        orderId: null,
        recycler: null,
        recyclerContact: null,
        endTime: null,
      },
      formItems: [
        { label: "废纸重量", model: "paper", resourceTypeId: 5 },
        { label: "废纸价格", model: "paperPrice", resourceTypeId: 5 },
        { label: "塑料重量", model: "plastic", resourceTypeId: 6 },
        { label: "塑料价格", model: "plasticPrice", resourceTypeId: 6 },
        { label: "玻璃重量", model: "glass", resourceTypeId: 7 },
        { label: "玻璃价格", model: "glassPrice", resourceTypeId: 7 },
        { label: "金属重量", model: "metal", resourceTypeId: 8 },
        { label: "金属价格", model: "metalPrice", resourceTypeId: 8 },
        { label: "布料重量", model: "cloth", resourceTypeId: 9 },
        { label: "布料价格", model: "clothPrice", resourceTypeId: 9 },
      ],
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.getMerchant();
    this.getListRrsource();
  },
  computed: {
    /** 是否展示按钮 */
    showButton() {
      return user.state.userType == "02";
    },
  },
  methods: {
    /** 查询申请列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then((response) => {
        this.orderList = response.rows;
        this.orderList.forEach((x) => {
          if (x.status == 0) {
            x.status = "进行中";
          } else if (x.status == 1) {
            x.status = "已完成";
          } else if (x.status == 2) {
            x.status = "已下单";
          } else {
            x.status = "已失效";
          }
        });

        this.total = response.total;
        this.loading = false;
      });
    },
    /** 按条件模糊搜索申请列表 */
    getFuzzyList() {
      this.loading = true;
      fuzzyListOrder(this.queryParams).then((response) => {
        this.orderList = response.rows;
        this.orderList.forEach((x) => {
          if (x.status == 0) {
            x.status = "进行中";
          } else if (x.status == 1) {
            x.status = "已完成";
          } else if (x.status == 2) {
            x.status = "已下单";
          } else {
            x.status = "已失效";
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 按条件搜索用户所拥有的资源列表 */
    getListRrsource() {
      listResource(this.queryParams).then((response) => {
        this.ownResources = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openRecycle = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderType: null,
        publisherId: null,
        finisherId: null,
        description: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        status: null,
        remark: null,
        searchValue: null,
      };
      this.recycleForm = {
        recycler: null,
        recyclerContact: null,
        endTime: null,
      };
      this.resetForm("form");
      this.resetForm("recycleForm");
    },
    /** 搜索商家列表 */
    getMerchant() {
      selectMerchant().then((response) => {
        this.merchant = response.rows;
      });
    },

    /** 控制显示已拥有资源 */
    showItem(item) {
      if (
        this.ownResources.some((x) => {
          return x.resourceTypeId == item.resourceTypeId;
        })
      ) {
        return true;
      }
      return false;
    },
    /**搜索历史申请 */
    handleHistory() {
      listHistory()
        .then((response) => {
          this.historyList = response.rows;
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "无法查看！请稍后重试",
          });
        });

      this.openHistory = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 模糊搜索按钮操作 */
    handleFuzzyQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.searchTime != null) {
        this.queryParams.beginDate = this.queryParams.searchTime[0];
        this.queryParams.endDate = this.queryParams.searchTime[1];
      }
      this.getFuzzyList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderId);
      this.publisherIds = selection.map((item) => item.publisherId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      if (user.state.userType == "02") {
        this.$alert("商家不能上报资源回收申请！", "警告", {
          confirmButtonText: "确认",
        });
        return;
      }
      this.reset();
      this.open = true;
      this.title = "新增申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (user.state.userId != this.publisherIds[0]) {
        this.$alert("只能修改自己发布的申请！", "警告", {
          confirmButtonText: "确认",
        });
        return;
      }
      this.reset();
      const orderId = this.ids;
      getOrder(orderId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改申请";
      });
    },
    /** 查看关联资源操作按钮 */
    viewDetail(row) {
      let Id = {
        orderId: row.orderId,
      };
      listOrderResource(Id)
        .then((response) => {
          this.relativeResource = response.rows;
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "无法查看！请稍后重试",
          });
        });

      this.openDetail = true;
    },

    /** 分配回收操作按钮 */
    allotRecycle(row) {
      this.reset();
      this.recycleForm.orderId = row.orderId;
      // if (user.state.userType != "02") {
      //   this.$alert("只有商家才能分配回收！", "警告", {
      //     confirmButtonText: "确认",
      //   });
      //   return;
      // }
      this.openRecycle = true;
    },
    /** 查看支付预览操作按钮 */
    viewPreview(row) {
      let Id = {
        orderId: row.orderId,
      };
      previewPay(Id)
        .then((response) => {
          this.previewList = response.rows;
          this.isPreview = true;
          this.previewList.forEach((item) => {
            item.percentage = this.toPercent(item.percentage);
          });
        })
        .catch((error) => {
          this.$message({
            type: "error",
            message: error,
          });
        });

      this.openPreview = true;
    },
    /** 完成支付操作按钮 */
    handleAccept(row) {
      this.$confirm("确定完成支付？该操作无法撤销", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(this.isPreview);
          if (this.previewList == false) {
            this.$alert("请先查看支付预览，确认后再完成支付！", "支付提示", {
              confirmButtonText: "确定",
            });
            return;
          }

          this.previewList.forEach((x) => {
            x.percentage = this.toPoint(x.percentage);
          });
          let data = {
            orderId: row.orderId,
            previewDetail: this.previewList,
            orderDetail: this.allotParams,
          };
          console.log("+++++");
          console.log(data);
          complete(data)
            .then(() => {
              this.$message({
                type: "success",
                message: "支付成功!",
              });
              this.getList();
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "支付失败！请稍后重试",
              });
              this.getList();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消支付",
          });
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.orderId != null) {
            this.form.publisherId = user.state.userId;
            updateOrder(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.publisherId = user.state.userId;

            addOrder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    submitRecycleForm() {
      this.$refs["recycleForm"].validate((valid) => {
        if (valid) {
          this.allotParams = this.recycleForm;
        }
        this.openRecycle = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete() {
      if (
        this.publisherIds.every((item) => {
          return item == user.state.userId;
        })
      ) {
        const orderIds = this.ids;
        this.$modal
          .confirm("是否确认删除选中申请")
          .then(function () {
            return delOrder(orderIds);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      } else {
        this.$alert("只能删除自己发布的申请！", "警告", {
          confirmButtonText: "确认",
        });
        return;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/order/export",
        {
          ...this.queryParams,
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },

    toPercent(point) {
      var percent = Number(point * 100).toFixed(2);
      percent += "%";
      return percent;
    },
    toPoint(percent) {
      var str = percent.replace("%", "");
      str = str / 100;
      return str;
    },
  },
};
</script>
